<template>
  <Dialog v-model="dialogVisible" title="菜单权限">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" label-width="80px">
      <el-form-item label="角色名称">
        <el-tag>{{ formData.name }}</el-tag>
      </el-form-item>
      <el-form-item label="角色编码">
        <el-tag>{{ formData.code }}</el-tag>
      </el-form-item>
      <el-form-item label="菜单权限">
        <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand">展开/折叠</el-checkbox>
        <el-checkbox v-model="menuCheckAll" @change="handleCheckedTreeCheckAll"
          >全选/全不选</el-checkbox
        >
        <el-checkbox v-model="menuCheckLinked">父子联动</el-checkbox>
        <el-tree
          ref="menuTreeRef"
          class="tree-border h-400px overflow-auto"
          :data="menuTree"
          :props="defaultProps"
          empty-text="加载中，请稍候"
          node-key="id"
          show-checkbox
          :check-strictly="!menuCheckLinked"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { defaultProps, handleTree } from '@/utils/tree'
import * as RoleApi from '@/api/system/role'
import * as MenuApi from '@/api/system/menu'
import * as PermissionApi from '@/api/system/permission'
import { EnableStatusEnum } from '@/utils/constants'

defineOptions({ name: 'SystemRoleAssignMenuForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined as any,
  name: '',
  code: '',
  menuIds: []
})
const formRef = ref() // 表单 Ref

const menuTree = ref() // 菜单树数据
const menuExpand = ref(false) // 是否展开
const menuCheckAll = ref(false) // 全选/全不选
const menuCheckLinked = ref(true) // 是否父子联动
const menuTreeRef = ref() // 菜单树组件

const open = async (role: RoleApi.RoleVO) => {
  dialogVisible.value = true
  resetForm()
  formData.value.id = role.id
  formData.value.name = role.name
  formData.value.code = role.code
  formLoading.value = true
  try {
    menuTree.value = handleTree(await MenuApi.getMenuSimpleList(EnableStatusEnum.Enabled))
    formData.value.menuIds = await PermissionApi.getRoleMenuIds(role.id!)
    nextTick(() => {
      // dom渲染完后再设置树节点状态
      formData.value.menuIds.forEach((menuId) => {
        // (key/data, checked, deep)
        menuTreeRef.value.setChecked(menuId, true, false)
      })
    })
  } finally {
    formLoading.value = false
  }
}

defineExpose({ open })

const emit = defineEmits(['success']) // 定义success事件，用于操作成功后的回调
const submitForm = async () => {
  if (await formValidate(formRef)) return
  formLoading.value = true
  try {
    const data = {
      roleId: formData.value.id,
      menuIds: [
        ...menuTreeRef.value.getCheckedKeys(false), // 获取到选中节点的keys(leafOnly: false， 不仅仅只包括leaf节点)
        ...menuTreeRef.value.getHalfCheckedKeys() // 获取半选中节点的keys(即其所有子节点未全部选中的节点)
      ]
    }
    await PermissionApi.assignRoleMenu(data)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  menuExpand.value = false
  menuCheckAll.value = false
  menuCheckLinked.value = true
  formData.value = {
    id: undefined,
    name: '',
    code: '',
    menuIds: []
  }
  menuTreeRef.value?.setCheckedNodes([])
  formRef.value?.resetFields()
}

const handleCheckedTreeExpand = () => {
  const nodes = menuTreeRef.value?.store.nodesMap
  for (const nodeKey in nodes) {
    if (nodes[nodeKey].expanded !== menuExpand.value) {
      nodes[nodeKey].expanded = menuExpand.value
    }
  }
}

const handleCheckedTreeCheckAll = () => {
  menuTreeRef.value?.setCheckedNodes(menuCheckAll.value ? menuTree.value : [])
}
</script>

<style scoped lang="scss"></style>
